<?php
namespace frontend\controllers;

use yii;
use common\components\Myhelpers;
use common\models\Order;
use common\models\Pay;
use common\models\User;
use common\models\Fund;
use common\models\Recharge;
use common\models\Product;
use common\models\ShoppingCart;
use common\models\Region;
use common\models\Systemconfig;
use common\components\alipay\Alipay;

class PaynotifyController extends FController
{
	public $enableCsrfValidation = false;  //必须加上此选项
	public $alipay_config;

	public function init()
    {
        parent::init();
        
        $config = Systemconfig::getConfigValue('alipay');

        $this->alipay_config = [
            // 支付完成异步通知调用地址
            'notify_url' => "http://".$_SERVER['HTTP_HOST']."/paynotify",
            // 支付完成同步返回地址
            'return_url' => "http://".$_SERVER['HTTP_HOST']."/order/payreturn",
            // 支付宝商家 ID
            'partner'      => $config['alipay_pid'],
            // 支付宝商家 KEY
            'key'          => $config['alipay_wap_key'],
            // 支付宝商家注册邮箱
            'seller_email' => $config['alipay_seller_email']
        ];
    }
    //Alipay异步通知返回方法
    public function actionIndex(){
        $alipay = new Alipay($this->alipay_config);
        
        $verify_result = $alipay->verifyCallback(TRUE);
        if($verify_result) {//验证成功

            $out_trade_no = $_POST['out_trade_no'];  //商户订单号

            $trade_no = $_POST['trade_no'];  //支付宝交易号
            
            $trade_status = $_POST['trade_status'];  //交易状态

            if($_POST['trade_status'] == 'TRADE_FINISHED' || $_POST['trade_status'] == 'TRADE_SUCCESS') {
            
                $order = Order::findOne($out_trade_no);
                $user_id = $order->user_id;

                $pay = Pay::find()->where(['relation_id' => $order->id])->one();
                $recharge = Recharge::find()->where(['relation_id' =>$pay->id])->one();

                //查重
                if($order->pay_status == 2){
                    exit("此订单已支付完成，不能重复操作");
                }

                //事务
                $transaction = Yii::$app->db->beginTransaction();
                try {
                    //1.修改支付表的状态
                    $res1 = Pay::updateAll([ 'status'=> 2 ],[ 'id' => $pay->id]);
                    //2.修改充值表的状态    支付宝交易流水号
                    $res2 = Recharge::updateAll(['status'=>2,'bank_serial_no'=>$trade_no],['id'=>$recharge->id]);
                    //3.修改订单表的支付状态  订单状态
                    $res3 = Order::updateAll(['order_status'=>2,'pay_status'=>2],[ 'id' => $order->id]);
                    //4.增加资金明细

                    /*--充值--*/
                    $data['user_id'] = $user_id;
                    $data['relation_id1'] = $recharge->id;
                    $data['relation_id2'] = $order->id;
                    $data['fund_type'] = 1;
                    $data['deal_money'] = $order->pay_fee;
                    $data['remark'] = '用户充值';
                    $data['update_time'] = date('Y-m-d H:i:s');

                    $res4 = $this->Addfund($data);
                    //操作USER表里面的available_money
                    $available_money = User::findOne($user_id)->available_money;

                    $res5 = User::updateAll(['available_money'=>($available_money+$order->pay_fee)],['id'=>$user_id]);
                    /*--支付--*/
                    $data['relation_id1'] = $pay->id;
                    $data['fund_type'] = 31;
                    $data['deal_money'] = -($order->pay_fee);
                    $data['remark'] = '用户支付';

                    $res6 = $this->Addfund($data);
                    $available_money = User::findOne($user_id)->available_money;

                    $res7 = User::updateAll(['available_money'=>($available_money-$order->pay_fee)],['id'=>$user_id]);
                    if($res1 && $res2 && $res3 && $res4 && $res5 && $res6 && $res7 ){
                        $transaction->commit();
                    }else{
                        $transaction->rollBack();    
                    }

                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }

            echo "success";     //请不要修改或删除
        }else {
            echo "fail";
        }
    }

    //资金记录添加
    public function Addfund($data){

        $fund_id = Myhelpers::getOrderID(12);//生成资金明细id

        $available_money = User::findOne($data['user_id'])->available_money;

        $fund = new Fund();
        $fund->id = $fund_id;
        $fund->user_id = $data['user_id'];
        $fund->relation_id1 = $data['relation_id1'];
        $fund->relation_id2 = $data['relation_id2'];
        $fund->fund_type = $data['fund_type'];
        $fund->deal_money = $data['deal_money'];

        if($data['fund_type'] == 1 || $data['fund_type'] ==3 || $data['fund_type'] == 11){
            $fund->available_money = $available_money+$data['deal_money'];
        }else{
            $fund->available_money = $available_money+$data['deal_money'];
        }
        $fund->remark = $data['remark'];
        $fund->create_time = date('Y-m-d H:i:s');

        return $fund->save();
    }
}